package com.cms.admin.action.common;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSONArray;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.push.model.v20160801.PushResponse;
import com.cms.admin.action.BaseAction;
import com.cms.admin.model.AdvertisementList;
import com.cms.admin.model.AdvertisementListData;
import com.cms.admin.model.AdvertisementListDataExample;
import com.cms.admin.model.AdvertisementListExt;
import com.cms.admin.model.PageBean;
import com.cms.admin.model.StuffList;
import com.cms.admin.model.StuffListExt;
import com.cms.admin.model.UserList;
import com.cms.admin.service.common.AdvertisementListService;
import com.cms.admin.service.common.EntityService;
import com.cms.admin.service.common.TemplateService;
import com.cms.admin.service.stuff.StuffService;
import com.cms.admin.util.AliPushUtil;
import com.cms.admin.util.Constants;
import com.opensymphony.xwork2.ModelDriven;

/**
 * Created by YYY-Work on 2017/5/4.
 */
public class AdvertisementListAction extends BaseAction implements ModelDriven<AdvertisementListExt> {

    private AdvertisementListService advertisementListService;
    private TemplateService templateService;
    private EntityService entityService;
    private StuffService stuffService;

    private AdvertisementListExt search = new AdvertisementListExt();
    private PageBean page;
    private Long advertisementID;
    private AdvertisementList advertisementList;

    private StuffList stuffList;
    
    //页面元素
    private ArrayList<AdvertisementListDataExample> advertisementListDatas = new ArrayList<AdvertisementListDataExample>();
    
    //需要更新的广告
    private ArrayList<AdvertisementListData> addAdvertisementListDatas = new ArrayList<AdvertisementListData>();


    public String ajaxQueryAdvertisementList() {
        LOG.info("Start ArticleAction process,method is ajaxQuery");
        LOG.debug("Action is:" + search.getAction());
        page = new PageBean(search.getCurrentPage(), search.getPageSize());
        List<AdvertisementList> advertisementLists = advertisementListService.queryAdvertisementList(page, search);

        String res = null;
        try {
            res = getQueryResult(advertisementLists, page);
            JSONObject o = new JSONObject();
            o.put("pageCount", page.getTotalPage());
            o.put("content", res);
            return ajaxJsonSuccessMessage(o);
        } catch (Exception e) {
            LOG.error("ajaxQueryHospitalList", e);
            return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
        }
    }

    /**
     * 新增广告
     * @return
     * @throws Exception
     */
    public String ajaxAddAdvertisementList() throws Exception {

        request= ServletActionContext.getRequest();
        String imgOSSPath =null;
		if (null != search.getAdvertisementImage() && null !=search.getAdvertisementImageFileName()) {
			 imgOSSPath=uploadAdertismentImg(search.getAdvertisementImage(),search.getAdvertisementImageFileName());
			  search.setAdvertisementPictureUrl(imgOSSPath);
	         // advertisementListService.addAdvertisement(search);
		}
        
        search.setCreateDate(new Date());
        search.setUpdateDate(new Date());
        search.setCreateUserid(((UserList)request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
        search.setUpdateUserid(((UserList)request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
        processUploadFile();
        advertisementListService.addAdvertisement(search,addAdvertisementListDatas);
        return "success";
    }
    
    /**
     * 修改广告
     * @return
     * @throws Exception
     */
    public String ajaxModifyAdvertisementList() throws Exception
    {
        processUploadFile();
        
        search.setCreateDate(new Date());
        search.setUpdateDate(new Date());
        search.setCreateUserid(((UserList)request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
        search.setUpdateUserid(((UserList)request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
        advertisementListService.modifyAdvertisementList(search,addAdvertisementListDatas);
        return "success";
    }

    
    /**
     * 图片上传
     * @throws Exception
     */
    public void processUploadFile() throws Exception {
    	
    	if (null != advertisementListDatas && advertisementListDatas.size() > 0) {

			for (int j = 0; j < advertisementListDatas.size(); j++) {
				
				AdvertisementListData tempAdvertisementListData = new AdvertisementListData();;
				//查看是否上传文件
				AdvertisementListDataExample tempAdvertisementListDataExample = advertisementListDatas.get(j);
				
				if (null !=tempAdvertisementListDataExample ) {
					
				

				if (null != tempAdvertisementListDataExample.getImg() && null != tempAdvertisementListDataExample.getImgFileName()) {
					tempAdvertisementListData.setDataImgUrl(uploadAdertismentDataImg(tempAdvertisementListDataExample.getImg(),
							tempAdvertisementListDataExample.getImgFileName()));
				} else {
					tempAdvertisementListData.setDataImgUrl(tempAdvertisementListDataExample.getDataImgUrl());
				}
				
				tempAdvertisementListData.setAdvertisementid(tempAdvertisementListDataExample.getAdvertisementid());
				tempAdvertisementListData.setDataDesc(tempAdvertisementListDataExample.getDataDesc());
				tempAdvertisementListData.setDataOrder(tempAdvertisementListDataExample.getDataOrder());
				tempAdvertisementListData.setDataName(tempAdvertisementListDataExample.getDataName());
				
				addAdvertisementListDatas.add(tempAdvertisementListData);
				}
			}
    	}

    	
    }
    
    public String requestAdvertisementList()
    {
        initBathPath();
        return "success";
    }

    public String requestAddAdvertisement()
    {
        initBathPath();
        return "success";
    }

    public String requestModAdvertisement()
    {
        advertisementList=advertisementListService.queryAdvertisementListById(advertisementID);
        if (null!=advertisementList&&null!=advertisementList.getRecommendStuffId())
		{
			stuffList=stuffService.queryStuffListById(advertisementList.getRecommendStuffId());
		}
        return "success";
    }

    private String getQueryResult(List<AdvertisementList> advertisementLists, PageBean page)
            throws Exception {
        initBathPath();
        HashMap map = new HashMap();
        map.put("advertisementList", advertisementLists);
        map.put("page", page);
        map.put("basePath",getBasePath());
        map.put("ss", "测试测试测试测试");

        String result = "";
        result = templateService.generateContentByFreeMarker(
                Constants.TEMPLATE_ADVERTISEMENTLIST_QUERY_RESULT, map);
        return result;
    }
    
    private String uploadAdertismentDataImg(File img,String fileName)
    {
        //后缀
        try {
            String tailSuffix = getExtension(fileName);
            String DIR="Advertisement/Data/"+System.currentTimeMillis()+tailSuffix;
            PutObjectResult result=uploadByOss(img,DIR);
            if (null!=result)
            {
                return DIR;
            }else
            {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }

    private String uploadAdertismentImg(File img,String fileName)
    {
        //后缀
        try {
            String tailSuffix = getExtension(fileName);
            String DIR="Advertisement/"+System.currentTimeMillis()+tailSuffix;
            PutObjectResult result=uploadByOss(img,DIR);
            if (null!=result)
            {
                return DIR;
            }else
            {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;
    }
    
    private String replaymessage;
    
	/**
	 * html发布
	 * @return
	 */
	public String publishAdvertisement()
	{
		//StuffList stuff=stuffService.selectStuffList(stuffID);
		
		 advertisementList=advertisementListService.queryAdvertisementListById(advertisementID);

		if (null ==advertisementList) {
			replaymessage ="发布失败!";
			return ERROR;
		}
		if (null ==advertisementList.getAdvertisementListData()||advertisementList.getAdvertisementListData().size()==0) {
			replaymessage ="无资源!发布失败!";
			return ERROR;
		}
		Long stuffId = advertisementList.getRecommendStuffId();
		HashMap map = new HashMap();
		if (null!=stuffId&&0!=stuffId) {
			
			StuffListExt example = new StuffListExt();
			example.setStuffid(stuffId);
			List<StuffListExt> list =stuffService.selectStuffList(new PageBean(0,1),example);
			if (null ==list||list.size()!=1) {
				replaymessage ="发布失败!";
				return ERROR;
			}else{
				map.put("stuffList", list.get(0));
			}
		}
		 
		map.put("advertisementList", advertisementList);
		map.put("advertisementListData", advertisementList.getAdvertisementListData());
		
		String htmlUrl = "";
		
		String shareHtmlUrl = "";
	    
		try {
			
			if (advertisementList.getPositionid().intValue()==2) {
				htmlUrl = uploadTemplate(templateService, advertisementList.getAdvertisementid().toString(), map,Constants.ADVERTISEMENT_TEMPLATE);
				
				shareHtmlUrl = uploadTemplate(templateService, advertisementList.getAdvertisementid().toString(), map,Constants.ADVERTISEMENT_SHARE_TEMPLATE);
			    
			}else if (advertisementList.getPositionid().intValue()==4) {
				
				
				map.put("url", advertisementList.getAdvertisementListData().get(0).getDataImgUrl());
			    htmlUrl = uploadTemplate(templateService, advertisementList.getAdvertisementid().toString(), map,Constants.ADVERTISEMENT_COOKBOOK_NEW_TEMPLATE);
				shareHtmlUrl = htmlUrl;
				
			}else{
				replaymessage ="不支持发布!";
				return ERROR;
			}
	
			search.setAdvertisementid(advertisementID);
			
			if (null!=stuffId&&0!=stuffId) {
				search.setClickLinkUrl(Constants.OSS_ADRESS+htmlUrl+"?stuffId="+stuffId);
				search.setShareLinkUrl(Constants.OSS_ADRESS+shareHtmlUrl+"?stuffId="+stuffId);
			}else{
				search.setClickLinkUrl(Constants.OSS_ADRESS+htmlUrl);
				search.setShareLinkUrl(Constants.OSS_ADRESS+shareHtmlUrl);
			}
		
	        search.setCreateDate(new Date());
	        search.setUpdateDate(new Date());
	        search.setCreateUserid(((UserList)request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
	        search.setUpdateUserid(((UserList)request.getSession().getAttribute(Constants.USER_OBJECT)).getUserid());
	        advertisementListService.modifyAdvertisementList(search);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			replaymessage ="发布失败!";
			e.printStackTrace();
			return ERROR;
		}
		replaymessage ="发布成功!";
		return SUCCESS;
	}
    
	
	/**
	 *	推送
	 * @return
	 */
	public String pushAdvertisement()
	{
		
		advertisementList=advertisementListService.queryAdvertisementListById(advertisementID);
		
		if (null ==advertisementList) {
			replaymessage ="信息错误!";
			return ERROR;
		}
		
		Map<String,String> map = new HashMap<String,String>();
		
		map.put("advertisementid",advertisementList.getAdvertisementid().toString());
		map.put("advertiseTag",advertisementList.getAdvertiseTag());
		map.put("advertisementDesc", advertisementList.getAdvertisementDesc());
		map.put("url", advertisementList.getClickLinkUrl());
		
		 try {
			PushResponse pushResponse = AliPushUtil.AdvancedPush(advertisementList.getAdvertisementDesc(), JSONArray.toJSONString(map));
		
			Long  messageId = Long.valueOf(pushResponse.getMessageId());
			
			if (messageId>0) {
				replaymessage ="推送成功!";
				return SUCCESS;
			}else{
				replaymessage ="推送错误!";
				return ERROR;
			}
		 } catch (Exception e) {
			// TODO Auto-generated catch block
			replaymessage ="推送错误!";
			return ERROR;
		}
	}
	
	/**
	 * 
	 * @return
	 */
	public String previewAdvertisement()
	{
		
		advertisementList=advertisementListService.queryAdvertisementListById(advertisementID);
		
		if (null ==advertisementList) {
			replaymessage ="信息错误!";
			return ERROR;
		}
		String htmlUrl = advertisementList.getClickLinkUrl();
		if (StringUtils.isBlank(htmlUrl)) {
			replaymessage ="链接错误，预览链接不存在!";
			return ERROR;
		}
		
		if (StringUtils.isNotEmpty(htmlUrl)) {
			HttpServletResponse resp = ServletActionContext.getResponse();
			
			try {
				resp.sendRedirect(htmlUrl);
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return null;
		}else{
			return ERROR;
		}
		
	}
	
	/**
	 * 文章发布
	 * @param templateService
	 * @param srcFileName
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public static String uploadTemplate(TemplateService templateService,String srcFileName, Map model,String template) throws Exception
	{
		
		// 获取相对于服务器的根目录
		getRootPath();

		// 开始处理上传文件
 
		//包括了原文件名的路径
		String srcFilePath="";
		
		//未包括目标文件名的路径
		String destPath = "";

		//包括了目标文件名的路径
		String destFilePath = "";
		//后缀
		srcFileName = System.currentTimeMillis()+".html";
		// 先设置一次目录，后面再做处理
		String savePath = contextPath;
	
		
		//要存储到的目录
		destPath =  savePath +File.separator;
		
		//得到一个随机的文件名
		String uniqueName= srcFileName;
		
		//相对URI
		String DIR ="Advertisement/Share/";
		destFilePath = savePath + File.separator+uniqueName;
		
		destFilePath = destPath+uniqueName;

		File dest = new File(destFilePath);
		
		System.out.println(DIR);

		// 如果目标目录不存在，则创建
		if (!fileExists(destPath)) {
			makeDir(destPath);
		}
		templateService.processCreateHtml(template, model, dest);
		//templateService.processCreateHtml(Constants.ADVERTISEMENT_TEMPLATE, model, dest);
		// 从临时目录生成文件到指定文件
		
		uploadByOssShare( dest, DIR);
		dest.delete();
		
		return DIR+srcFileName;
	}
	
	
	

    public String getReplaymessage() {
		return replaymessage;
	}

	public void setReplaymessage(String replaymessage) {
		this.replaymessage = replaymessage;
	}

	@Override
    public AdvertisementListExt getModel() {
        return search;
    }

    public TemplateService getTemplateService() {
        return templateService;
    }

    public void setTemplateService(TemplateService templateService) {
        this.templateService = templateService;
    }

    public EntityService getEntityService() {
        return entityService;
    }

    public void setEntityService(EntityService entityService) {
        this.entityService = entityService;
    }

    public AdvertisementListService getAdvertisementListService() {
        return advertisementListService;
    }

    public void setAdvertisementListService(AdvertisementListService advertisementListService) {
        this.advertisementListService = advertisementListService;
    }

    public AdvertisementList getAdvertisementList() {
        return advertisementList;
    }

    public void setAdvertisementList(AdvertisementList advertisementList) {
        this.advertisementList = advertisementList;
    }

    public Long getAdvertisementID() {
        return advertisementID;
    }

    public void setAdvertisementID(Long advertisementID) {
        this.advertisementID = advertisementID;
    }


	public ArrayList<AdvertisementListDataExample> getAdvertisementListDatas() {
		return advertisementListDatas;
	}


	public void setAdvertisementListDatas(
			ArrayList<AdvertisementListDataExample> advertisementListDatas) {
		this.advertisementListDatas = advertisementListDatas;
	}


	public ArrayList<AdvertisementListData> getAddAdvertisementListDatas() {
		return addAdvertisementListDatas;
	}


	public void setAddAdvertisementListDatas(
			ArrayList<AdvertisementListData> addAdvertisementListDatas) {
		this.addAdvertisementListDatas = addAdvertisementListDatas;
	}

	public StuffService getStuffService() {
		return stuffService;
	}

	public void setStuffService(StuffService stuffService) {
		this.stuffService = stuffService;
	}

	public StuffList getStuffList() {
		return stuffList;
	}

	public void setStuffList(StuffList stuffList) {
		this.stuffList = stuffList;
	}
}
